package ua.exchangeratesukraine.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.actions.DataTask;
import ua.exchangeratesukraine.actions.WorkDB;
import ua.exchangeratesukraine.adapter.BanksAdapter;
import ua.exchangeratesukraine.model.CurrencyModel;
import ua.exchangeratesukraine.util.Constants;
import ua.exchangeratesukraine.util.Util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class FragmentBanks extends FragmentBase {

	private String			LOG_TAG				= getClass().getSimpleName();
	private String[]		currencyTypeArray	= null;
	private String[]		currencyCodeArray	= null;
	private String[]		bankNames			= null;
	private List<String>	bankNamesOrig		= new ArrayList<String>();
	private String			URL_BANKS			= "";
	private String			bankName			= "";
	private String			bankCode			= "";
	private String			tableName			= Constants.TABLE_NAME_BANKS;
	private int				position			= 0;

	@Override
	public void onAttach(Activity activity) {
		wdb = new WorkDB();
		wdb.createDB(getActivity());
		wdb.createTable(tableName);
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {

		View view = inflater.inflate(R.layout.fragment_banks, null);

		currencyTypeArray = getActivity().getResources().getStringArray(R.array.currency_type);
		currencyCodeArray = getActivity().getResources().getStringArray(R.array.currency_type_code);

		listHeader = inflater.inflate(R.layout.list_header_banks, null);
		listFooter = inflater.inflate(R.layout.list_footer, null);
		tvCurrentDate = (TextView) view.findViewById(R.id.tvCurrentDate);
		btnResult = (Button) view.findViewById(R.id.btnResult);
		tvSetBank = (TextView) view.findViewById(R.id.tvSetBank);
		tvDate = (TextView) view.findViewById(R.id.tvDate);
		bar = (ProgressBar) view.findViewById(R.id.progressBar);
		bar.setVisibility(View.INVISIBLE);
		tvCurrentDate.setOnClickListener(this);
		tvSetBank.setOnClickListener(this);
		tvCurrentDate.setOnTouchListener(this);
		tvSetBank.setOnTouchListener(this);
		btnResult.setOnClickListener(this);
		btnResult.setOnTouchListener(this);

		// Adapter
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, R.layout.spinner_item,
				currencyTypeArray);
		adapter.setDropDownViewResource(R.layout.spinner_item_dropdown);

		Spinner currencySpinner = (Spinner) view.findViewById(R.id.currencySpinner);
		currencySpinner.setAdapter(adapter);

		// click listener for spinner
		currencySpinner.setOnItemSelectedListener(this);

		return view;
	}

	protected boolean getIsOneBank() {
		return isOneBank;
	}

	protected void setIsOneBank(boolean isOneBank) {
		this.isOneBank = isOneBank;
	}

	@Override
	public void onActivityCreated(Bundle inState) {
		super.onActivityCreated(inState);

		date = getCurrentDate();
		bankNames = getResources().getStringArray(R.array.bank_names);
		bankName = bankNames[0];

		if (inState != null) {

			isRotate = true;
			date = inState.getString(Constants.DATE);
			prevDate = inState.getString(Constants.PREV_DATE);
			isListShow = inState.getBoolean(Constants.IS_LIST_SHOW);
			isDialogShow = inState.getBoolean(Constants.IS_DIALOG_SHOW);
			bankName = inState.getString(Constants.BANK_NAME);
			bankCode = inState.getString(Constants.BANK_CODE);
			currencyModelArray = inState.getParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY);

			if ( isListShow && !currencyModelArray.isEmpty() && !hasHeader) {
				getListView().addHeaderView(listHeader);
				getListView().addFooterView(listFooter);
			}

			if (adapter == null)
				adapter = getAdapter();

			setListAdapter(adapter);
			if (isDialogShow)
				showBankDialog();

			fillTvDate(" " + getString(R.string.text_on_date) + " " + prevDate);
		}
		
		tvSetBank.setText(bankName);
		fillTvCurrentDate(date);
	}

	private void showBankDialog() {
		
		Object response = wdb.read(Constants.DATE_DEFAULT, tableName, "");
		if (!response.getClass().equals(Boolean.class)){
			Log.d(LOG_TAG, "bankNames EXIST");
			bankNames = (String[]) response;
		}
		else{
			if (bankNames.length < currencyModelArray.size()) {
			List<String> bankNamesList = new ArrayList<String>();
			if (!currencyModelArray.isEmpty()) {
				bankNamesList.add(getActivity().getString(R.string.tv_title_banks_list));
				for (CurrencyModel currencyModel : currencyModelArray) {
					bankNamesList.add(currencyModel.getName());
				}
				bankNames = new String[bankNamesList.size()];
				bankNames = bankNamesList.toArray(bankNames);
			}
				wdb.addToDB(bankNames, date, tableName, "type");
			}
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.bank_dialog_text);
		builder.setItems(bankNames, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int pos) {
				bankName = bankNames[pos];
				Log.d(LOG_TAG, "bankName : " + bankName + " ; bankCode : " + bankCode + "\n");
				tvSetBank.setText(bankName);
				isDialogShow = false;
				if (pos != 0){
					isOneBank = true;
					position = pos;
				}else{
					isOneBank = false;
				}
				if (bankNames.length != 0)
					Log.d(LOG_TAG, "Selected Bank : " + bankNames[pos]);
			}
		});
		builder.show();
		isDialogShow = true;
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		// display selected item position
		for (int i = 0; i < currencyTypeArray.length; i++) {
			if ((parent.getSelectedItem().toString()) == currencyTypeArray[i]) {
				currencyCode = currencyCodeArray[i];
			}
		}
	}

	@Override
	public void onClick(View v) {
		
		currentTime = (new Date()).getTime();
		if( (currentTime - prevTime) < 700 )
			return;
		
		switch (v.getId()) {
			case R.id.tvCurrentDate:
				showDateDialog();
				break;
			case R.id.tvSetBank:
				showBankDialog();
				break;
			case R.id.btnResult:

				if(checkDate())
					return;
				
				fillTvCurrentDate(date);
				
				Object response = null;
				response = wdb.read(date, tableName, currencyCode);
				if (!response.getClass().equals(Boolean.class)) {
					state = Constants.STATE_FROM_DB;
					isOneBank = getIsOneBank();
					setData(response, null, state);
				} else {
					isNetworkAvailable = Util.isNetworkAvailable(context);
					if (!isNetworkAvailable) {
						showToast(getString(R.string.title_toast_connection_error),
									getString(R.string.text_toast_connection_error), 2);
						return;
					}
					// get data from server
					toServer(wdb);
				}
				break;
			default:
				break;
		}
		prevTime = currentTime;
	}

	public void toServer(WorkDB wdb) {

		URL_BANKS = BASE_URL + "/kursy-valut/cash_xml/?id=" + WEB_ID 
							 + "&currency=" + currencyCode + "&date=" + date;
//		URL_BANKS = BASE_URL + "/kursy-valut/cash_xml/?id=" + WEB_ID + "&currency=" + currencyCode + "&date=" + date
//				+ "&bank=" + bankCode;
		Log.d(LOG_TAG, "URL_BANKS = \n" + URL_BANKS);


		DataTask mTask = new DataTask(context, this, wdb);
		mTask.execute(URL_BANKS, date, tableName);
	}

	@Override
	public void sortFragment(View view, boolean isFirstRequest) {
		sort(view,  isFirstRequest);
		initArray();
	}
	
	public void sort(final View view, boolean isRequest) {
		currencyModelArray = Util.sortBanks(view, currencyModelArray, isRequest);
	}

	@Override
	protected ArrayList<CurrencyModel> getDataForOneBank(ArrayList<CurrencyModel> currencyModelArray) {

		ArrayList<CurrencyModel> tmp = new ArrayList<CurrencyModel>();
		for (CurrencyModel currencyModel : currencyModelArray) {
			if ( (currencyModel.getName()).equalsIgnoreCase(bankName) )
				tmp.add(currencyModel);
			
		}
		return tmp;
	}

	protected void setCurrencyModelArray(ArrayList<CurrencyModel> currencyModelArray){
		this.currencyModelArray = currencyModelArray;
	}

	@Override
	protected BanksAdapter getAdapter() {
		return new BanksAdapter(context, currencyModelArray, bankNames);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {

		outState.putBoolean(Constants.IS_LIST_SHOW, isListShow);
		outState.putBoolean(Constants.IS_DIALOG_SHOW, isDialogShow);
		outState.putString(Constants.DATE, date);
		outState.putString(Constants.PREV_DATE, prevDate);
		outState.putString(Constants.BANK_NAME, bankName);
		outState.putString(Constants.BANK_CODE, bankCode);
		outState.putString(Constants.BANK_NAME_CURRENT, bankName);
		outState.putParcelableArrayList(Constants.CURRENCY_MODEL_ARRAY, currencyModelArray);
		super.onSaveInstanceState(outState);
	}

	@Override
	public String getTableName() {
		return tableName;
	}
}